package com.zx.jhpt.login;

import com.zx.framework.core.util.DatetimeUtils;

import com.zx.framework.core.util.StringUtil;
import com.zx.framework.plat.login.LoginAdapterController;
import com.zx.jhpt.po.Fxfkjz;
import com.zx.jhpt.service.EnclosureService;
import com.zx.jhpt.service.FxfkjzService;
import com.zx.jhpt.vo.FxfkjzVo;
import com.zx.jhpt.vo.ReplymessageVo;
import com.zx.jhpt.vo.JhptConts;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
public class FxfkjzController extends LoginAdapterController {

	private static final Logger LOGGER = Logger.getLogger(FxfkjzController.class);
	
	@Resource
	private FxfkjzService fxfkjzService;
	@Resource
	private EnclosureService enclosureService;
	
	private static Map<String, String> fengxiandengji = new HashMap<String, String>();
	static {
		fengxiandengji.put("h1", "高风险");
		fengxiandengji.put("h2", "中风险");
		fengxiandengji.put("h3", "低风险");
	}
	
	/**
	 * 风险报表
	 * @return
	 */
	
	/*@RequestMapping("/analysis")
	public String analysis(FxfkjzVo example,Model model){
		if (example == null) {
			example = new FxfkjzVo();
		}
		Date date = new Date();
		if (StringUtil.isEmpty(example.getHcsj().toString())) {
			example.setHcsj(DatetimeUtils.dateToString(date, "yyyy-MM"));
			//DatetimeUtils.stringToDate("", pattern);
			//example.setHcsj(date);
		}
		String fxdj = "";
		if (StringUtil.isNotEmpty(example.getFxdj())) {
			fxdj = example.getFxdj();
			example.setFxdj(fengxiandengji.get(fxdj));
		}
		List<Map> datas = fxfkjzService.analysis(example);
		String temp = "";//记录风险ID
        int row = 1;
        int rowsn = 0;
        for (int i = 0; i < datas.size(); i++) {
        	Map map = datas.get(i);
        	if(map.get("SFTGHZD") != null && map.get("SFTGHZD").toString().equals(JhptConts.REPLYMESSAGE_SFTGHZD_TRUE)){
				List<Map> enclosures = enclosureService.getFujian(map.get("REPLID"), map.get("HCSJ"), JhptConts.ENCLOSURE_TYPE_HZ, map.get("DEPTID"), map.get("ID"));
				map.put("enclosures", enclosures);
			}
        	try {
        		//计算要合并的行数
            	if(StringUtil.isEmpty(temp)){
                	temp = map.get("ID").toString();
                	row = 1;
                }
            	boolean flag = false;
            	if (datas.size()-1 >= i+1 && !temp.equals(datas.get(i+1).get("ID").toString())) {
            		flag = true;
				}
            	if (i == datas.size() - 1) {
            		flag = true;
				}
            	if (flag) {
            		datas.get(rowsn).put("ROWS", row);
            		rowsn += row;
            		temp = null;
				}
			} catch (Exception e) {
				LOGGER.error("计算合并行数失败：",e);
			}
        	
        	row++;
        }
		example.setFxdj(fxdj);
		List<String> dates = new ArrayList<String>();
		for (int i = 0; i <= 4; i++) {
			dates.add(DatetimeUtils.dateToString(DateUtils.addMonths(date, -i), "yyyy-MM"));
		}
		model.addAttribute("datas", datas);//将查询到的台帐信息传到前台
		model.addAttribute("dates", dates);//将稽查月份传到前台
		List<Fxfkjz> fxfkjzs = fxfkjzService.getAll();//查询所有的风险点
		model.addAttribute("fxfkjzs", fxfkjzs);//将查询结果传到页面上
		model.addAttribute("example", example);//将replymessage信息传到页面
		
		model.addAttribute("fengxiandengji", fengxiandengji);
		return "analysis";
	}*/
	
	/**
	 * 风险报表--台帐
	 * @param example
	 * @param model
	 * @return
	 */
	@RequestMapping("/analysis")
	public String analysis(FxfkjzVo example,Model model){
		if (example == null) {
			example = new FxfkjzVo();
		}
		Date date = new Date();
		if (StringUtil.isEmpty(example.getHcsj())) {
			example.setHcsj(DatetimeUtils.dateToString(date, "yyyy-MM"));
		}
		String fxdj = "";
		if (StringUtil.isNotEmpty(example.getFxdj())) {
			fxdj = example.getFxdj();
			example.setFxdj(fengxiandengji.get(fxdj));
		}
		List<Map> datas = fxfkjzService.analysis(example);
		String temp = "";//记录风险ID
        int row = 1;
        int rowsn = 0;
        for (int i = 0; i < datas.size(); i++) {
        	Map map = datas.get(i);
        	if(map.get("SFTGHZD") != null && map.get("SFTGHZD").toString().equals(JhptConts.REPLYMESSAGE_SFTGHZD_TRUE)){
				List<Map> enclosures = enclosureService.getFujian(map.get("REPLID"), map.get("HCSJ"), JhptConts.ENCLOSURE_TYPE_HZ, map.get("DEPTID"), map.get("ID"));
				map.put("enclosures", enclosures);
			}
        	try {
        		//计算要合并的行数
            	if(StringUtil.isEmpty(temp)){
                	temp = map.get("ID").toString();
                	row = 1;
                }
            	boolean flag = false;
            	if (datas.size()-1 >= i+1 && !temp.equals(datas.get(i+1).get("ID").toString())) {
            		flag = true;
				}
            	if (i == datas.size() - 1) {
            		flag = true;
				}
            	if (flag) {
            		datas.get(rowsn).put("ROWS", row);
            		rowsn += row;
            		temp = null;
				}
			} catch (Exception e) {
				LOGGER.error("计算合并行数失败：",e);
			}
        	
        	row++;
        }
		example.setFxdj(fxdj);
		List<String> dates = new ArrayList<String>();
		for (int i = 0; i <= 4; i++) {
			dates.add(DatetimeUtils.dateToString(DateUtils.addMonths(date, -i), "yyyy-MM"));
		}
		model.addAttribute("datas", datas);
		model.addAttribute("dates", dates);
		List<Fxfkjz> fxfkjzs = fxfkjzService.getAll();
		model.addAttribute("fxfkjzs", fxfkjzs);
		model.addAttribute("example", example);
		
		model.addAttribute("fengxiandengji", fengxiandengji);
		return "analysis";
	}
	
	@RequestMapping("/anaydownload")    
    public void download(FxfkjzVo example,HttpServletResponse response) {
    	if (example == null) {
			example = new FxfkjzVo();
		}
		Date date = new Date();
		if (StringUtil.isEmpty(example.getHcsj())) {
			example.setHcsj(DatetimeUtils.dateToString(date, "yyyy-MM"));
		}
		if (StringUtil.isNotEmpty(example.getFxdj())) {
			example.setFxdj(fengxiandengji.get(example.getFxdj()));
		}
        javax.servlet.ServletOutputStream sos = null;
		try {
			String fileName = "风险报表("+DatetimeUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss")+").xls";
			List<Map> datas = fxfkjzService.analysis(example);
	    	HSSFWorkbook file = fxfkjzService.analdownload(datas);
			sos = response.getOutputStream();
			response.reset(); // 必要地清除response中的缓存信息
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename=".concat(new String(fileName.getBytes("gb2312"),"iso8859-1")));
            file.write(sos);//导出excel白件
            sos.flush();
            sos.close();//封闭输出
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (sos!=null) {
				try {
					sos.close();
				} catch (IOException e) {}
			}
		}
    }

    /**
     * 查询所有风控点
     * @return 风控点列表
     */
    @RequestMapping("/findAllFxfkjz")
    @ResponseBody
    public List<Fxfkjz> findAllFxfkjz(){
        return fxfkjzService.getAll();
    }
}
